<template>
  <div class="login-container">
    <div class="login-box">
      <div class="close-btn" @click="goBack">
        <el-icon><Close /></el-icon>
      </div>
      
      <h1 class="login-title">用户登录</h1>
      
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="rules"
        class="login-form"
      >
        <div class="form-label">用户名：</div>
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
          >
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <div class="form-label">密码：</div>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <div class="form-label">选择角色：</div>
        <el-form-item prop="role">
          <el-radio-group v-model="loginForm.role" class="role-group">
            <el-radio :label="1">会议组织者</el-radio>
            <el-radio :label="0">参会人员</el-radio>
          </el-radio-group>
        </el-form-item>

        <div class="form-options">
          <el-checkbox v-model="rememberMe">记住我</el-checkbox>
          <el-button link type="primary" class="forgot-link">忘记密码？</el-button>
        </div>

        <el-button
          type="primary"
          class="submit-btn"
          :loading="loading"
          @click="handleLogin"
        >
          {{ loading ? '登录中...' : '登录' }}
        </el-button>

        <div class="form-footer">
          还没有账号？
          <el-button link type="primary" @click="router.push('/register')" class="register-link">
            立即注册
          </el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { User, Lock, Close } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import { useRouter } from 'vue-router'

const loginFormRef = ref(null)
const loading = ref(false)
const rememberMe = ref(false)
const router = useRouter()

const loginForm = reactive({
  username: '',
  password: '',
  role: 0  // 默认选择参会人员
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 50, message: '用户名长度在 3 到 50 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_-]+$/, message: '用户名只能包含字母、数字、下划线和连字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 64, message: '密码长度在 6 到 64 个字符', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择登录角色', trigger: 'change' }
  ]
}

// const emit = defineEmits(['login-success', 'to-register', 'close'])

const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    await loginFormRef.value.validate()
    loading.value = true
    
    // 构造登录请求数据
    const loginData = {
      username: loginForm.username.trim(),
      password: loginForm.password,
      permissionId: loginForm.role
    }
    
    console.log('发送登录请求:', {
      ...loginData,
      password: loginData.password.length + '位密码'  // 不输出实际密码，只显示长度
    })
    
    const response = await request({
      url: '/api/auth/login',
      method: 'post',
      data: loginData
    })

    console.log('登录响应:', {
      ...response,
      token: response.token ? '已返回' : null
    })

    // 检查响应状态
    if (response.success && response.user) {
      // 验证返回的权限ID
      const userPermissionId = response.user.permissionId
      if (userPermissionId !== loginForm.role) {
        const roleText = loginForm.role === 1 ? '会议组织者' : '参会人员'
        ElMessage.error(`您没有${roleText}的权限，请选择正确的角色`)
        return
      }
      
      // 存储用户信息
      const userInfo = {
        userId: response.user.userId,
        username: response.user.username,
        permissionId: userPermissionId,
        fullName: response.user.fullName || '',
        email: response.user.email || '',
        phone: response.user.phone || '',
        avatar: response.user.avatar || '',
        position: response.user.position || '工作人员',  // 设置默认值
        department: response.user.department || '',
        age: response.user.age || null,
        remark: response.user.remark || '',
        createTime: response.user.createTime || new Date().toISOString()  // 设置默认值为当前时间
      }
      
      localStorage.setItem('token', response.token)
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
      
      const roleText = userPermissionId === 1 ? '会议组织者' : '参会人员'
      ElMessage.success(`登录成功！欢迎${roleText}：${response.user.fullName || response.user.username}`)
      
      // 根据权限跳转
      router.push(userPermissionId === 1 ? '/conferences' : '/dashboard')
    } else {
      ElMessage.error(response.message || '登录失败，请检查用户名和密码')
    }
  } catch (error) {
    console.error('登录失败:', error)
    if (error.response) {
      switch (error.response.status) {
        case 400:
          ElMessage.error(error.response.data?.message || '请求参数错误，请检查输入')
          break
        case 401:
          ElMessage.error('用户名或密码错误')
          break
        case 403:
          ElMessage.error('账号权限不足')
          break
        case 500:
          ElMessage.error('服务器内部错误，请联系管理员')
          break
        default:
          ElMessage.error(error.response.data?.message || '登录失败，请稍后重试')
      }
    } else {
      ElMessage.error('网络连接失败，请检查网络设置')
    }
  } finally {
    loading.value = false
  }
}

// 添加回退方法
const goBack = () => {
  console.log('返回上一页')
  router.back()
}
</script>

<style scoped>
.login-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(8px);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

.login-box {
  width: 400px;
  background: white;
  border-radius: 16px;
  padding: 40px;
  position: relative;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

.close-btn {
  position: absolute;
  top: 16px;
  right: 16px;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  background: rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.close-btn:hover {
  background: rgba(0, 0, 0, 0.2);
  transform: rotate(90deg);
}

.login-title {
  font-size: 32px;
  text-align: center;
  margin-bottom: 40px;
  background: linear-gradient(45deg, #1890ff, #36cfc9);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  font-weight: 600;
}

.form-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
  font-weight: 500;
}

.login-form :deep(.el-input__wrapper) {
  background-color: #f5f7fa;
  border-radius: 8px;
  height: 44px;
}

.login-form :deep(.el-input__inner) {
  height: 44px;
}

.login-form :deep(.el-input__prefix) {
  font-size: 18px;
  color: #909399;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 20px 0;
}

.forgot-link {
  font-size: 14px;
}

.submit-btn {
  width: 100%;
  height: 44px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  margin: 20px 0;
  background: linear-gradient(45deg, #1890ff, #36cfc9);
  border: none;
}

.submit-btn:hover {
  opacity: 0.9;
  transform: translateY(-1px);
}

.form-footer {
  text-align: center;
  font-size: 14px;
  color: #606266;
}

.register-link {
  font-weight: 500;
  font-size: 14px;
}

.role-group {
  width: 100%;
  display: flex;
  justify-content: space-around;
  margin: 10px 0;
}

.role-group :deep(.el-radio) {
  margin-right: 0;
}

@media screen and (max-width: 480px) {
  .login-box {
    width: 90%;
    padding: 30px 20px;
  }
  
  .login-title {
    font-size: 28px;
    margin-bottom: 30px;
  }
}
</style> 